'use strict';
const Sequelize = require('sequelize');
const Op = Sequelize.Op;

module.exports = (app) => {
  class ProjectService extends app.Service {
    async create() {
      const { app, ctx } = this;
      const { Project } = app.model.Tables.Shop;
      const dataObj = ctx.request.body;
      dataObj.user_id = ctx.adminInfo.id;

      try {
        const result = await Project.create(dataObj);
        return result;
      } catch (error) {
        return error.message ? error.message : error;
      }
    }

    async index() {
      const { app, ctx } = this;
      const { Project } = app.model.Tables.Shop;
      const { Admin } = app.model.Tables.Com;
      const userData = ctx.adminInfo || ctx.userInfo;
      let where = {
        user_id:
          (ctx.query.hasOwnProperty('id') && ctx.query.id) || userData.id,
      };

      // 如果存在name，代表使用查询功能，则不需要用户ID来进行选择
      if (ctx.query.hasOwnProperty('name')) {
        where = {
          name: {
            [Op.like]: `%${ctx.query.name}%`,
          },
        };
      }

      // 如果type为3且请求参数为getall，则为管理员获取所有项目的请求，所以清空where条件
      if (userData.type === '3' && ctx.query.getall) {
        where = {};
      }

      try {
        const res = await Project.findAll({
          order: [['id', 'DESC']],
          where,
          include: {
            model: Admin,
            attributes: ['name'],
          },
        });

        if (res.length === 0) {
          res.push({ dataValues: [] });
        }

        return res;
      } catch (error) {
        return error.message ? error.message : error;
      }
    }

    async getProjectById() {
      const { app, ctx } = this;
      const { Project } = app.model.Tables.Shop;
      const { Admin } = app.model.Tables.Com;
      const data = ctx.query;
      //获取token
      const token = ctx.get('authorization');
      let aRes = await Admin.findOne({
        where: {
          token: token,
        },
      });

      if (aRes.dataValues.type == 3) {
        let res = await Project.findByPk(data.project_id, {
          include: [{ model: Admin }],
        });
        // console.log(res);
        return res;
      } else {
        return '您不是超级管理员';
      }
    }
  }
  return ProjectService;
};
